package com.dbky.alg.browser.controller;

import com.dbky.alg.browser.support.SimpleResponse;
import com.dbky.alg.core.properties.AlgSecurityProperties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: tianchao
 * @Date: 2021/12/11 14:08
 * @Description:
 */
@RestController
public class BrowserSecurityController {

    Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * hello -> /login(/authentication/require)
     * hello 没权限后 在重定向之前存储了hello请求的信息
     * ExceptionTranslationFilter 184行代码
     */
    private RequestCache requestCache = new HttpSessionRequestCache();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private AlgSecurityProperties algSecurityProperties;

    /**
     * 当需要身份认证跳转到这里
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest != null) {
            String targetURL = savedRequest.getRedirectUrl();
            logger.info("引发跳转的请求是: {}", targetURL);
            if (StringUtils.endsWith(targetURL, ".html")){
                logger.error("预料不到的");
                redirectStrategy.sendRedirect(request, response, algSecurityProperties.getBrowser().getLoginPage());
                return null;
            }
        }
        return new SimpleResponse("访问的服务需要认证,引导用户去到登录页");
    }



    @GetMapping("/session/invalid")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public SimpleResponse sessionInvalid(){
        String message = "session失效";
        return new SimpleResponse(message);
    }
}
